#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
简单测试Chrome浏览器和WebDriver是否正常工作
"""

import os
import sys
import platform
import subprocess
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

def test_chrome_browser():
    """
    测试Chrome浏览器的连接情况
    1. 检测Chrome浏览器版本
    2. 尝试不同方法初始化ChromeDriver
    3. 打开百度测试页面
    """
    print("=" * 60)
    print("Chrome浏览器配置测试工具")
    print("=" * 60)
    
    # 检测Chrome浏览器版本
    print("检测Chrome浏览器版本...")
    chrome_path = None
    chrome_version = None
    
    if platform.system() == "Darwin":  # macOS
        chrome_path = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
        try:
            result = subprocess.run([chrome_path, "--version"], capture_output=True, text=True)
            chrome_version = result.stdout.strip()
            print(f"✓ 检测到Chrome浏览器: {chrome_version}")
        except Exception as e:
            print(f"✗ 无法获取Chrome版本: {str(e)}")
    elif platform.system() == "Windows":
        chrome_paths = [
            "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
            "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
        ]
        for path in chrome_paths:
            if os.path.exists(path):
                chrome_path = path
                try:
                    result = subprocess.run([path, "--version"], capture_output=True, text=True)
                    chrome_version = result.stdout.strip()
                    print(f"✓ 检测到Chrome浏览器: {chrome_version}")
                    break
                except Exception as e:
                    print(f"✗ 无法获取Chrome版本: {str(e)}")
    else:  # Linux
        try:
            result = subprocess.run(["google-chrome", "--version"], capture_output=True, text=True)
            chrome_version = result.stdout.strip()
            chrome_path = "/usr/bin/google-chrome"
            print(f"✓ 检测到Chrome浏览器: {chrome_version}")
        except Exception as e:
            print(f"✗ 无法获取Chrome版本: {str(e)}")
    
    if not chrome_path or not chrome_version:
        print("✗ 未找到Chrome浏览器，请安装最新版Chrome后重试")
        return
    
    # 设置ChromeDriver
    print("\n设置ChromeDriver...")
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    
    # 尝试不同的方法初始化ChromeDriver
    print("\n尝试不同方法初始化ChromeDriver:")
    
    # 方法1: 直接使用系统路径
    print("\n方法1: 使用系统Chrome浏览器")
    try:
        print("创建Service对象...")
        service = Service()
        
        print("初始化Chrome WebDriver...")
        driver = webdriver.Chrome(service=service, options=options)
        print("✓ 方法1成功: 使用系统Chrome浏览器初始化成功")
        
        # 测试打开网页
        print("\n测试打开百度...")
        driver.get("https://www.baidu.com")
        print(f"✓ 成功打开网页，当前标题: {driver.title}")
        
        # 关闭浏览器
        driver.quit()
        print("✓ 测试完成，浏览器已关闭")
        return
    except Exception as e:
        print(f"✗ 方法1失败: {str(e)}")
    
    # 方法2: 查找可能的ChromeDriver路径
    print("\n方法2: 查找可能的ChromeDriver路径")
    
    if platform.system() == "Darwin":  # macOS
        paths = [
            "/usr/local/bin/chromedriver",
            os.path.expanduser("~/chromedriver"),
            "/opt/homebrew/bin/chromedriver"
        ]
    elif platform.system() == "Windows":
        paths = [
            "C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe",
            "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe",
            os.path.join(os.getcwd(), "chromedriver.exe")
        ]
    else:  # Linux
        paths = [
            "/usr/bin/chromedriver",
            "/usr/local/bin/chromedriver",
            os.path.join(os.getcwd(), "chromedriver")
        ]
    
    for path in paths:
        if os.path.exists(path):
            print(f"找到可能的ChromeDriver路径: {path}")
            try:
                service = Service(executable_path=path)
                driver = webdriver.Chrome(service=service, options=options)
                print(f"✓ 方法2成功: 使用找到的路径 {path} 初始化成功")
                
                # 测试打开网页
                print("\n测试打开百度...")
                driver.get("https://www.baidu.com")
                print(f"✓ 成功打开网页，当前标题: {driver.title}")
                
                # 关闭浏览器
                driver.quit()
                print("✓ 测试完成，浏览器已关闭")
                return
            except Exception as e:
                print(f"✗ 使用路径 {path} 初始化失败: {str(e)}")
    
    # 方法3: 尝试安装并使用webdriver-manager
    print("\n方法3: 尝试使用webdriver-manager")
    try:
        print("检查webdriver-manager包...")
        try:
            from webdriver_manager.chrome import ChromeDriverManager
            print("✓ 已安装webdriver-manager")
        except ImportError:
            print("✗ 未安装webdriver-manager，尝试安装...")
            subprocess.check_call([sys.executable, "-m", "pip", "install", "webdriver-manager"])
            from webdriver_manager.chrome import ChromeDriverManager
            print("✓ 成功安装webdriver-manager")
        
        print("使用webdriver-manager下载ChromeDriver...")
        driver_path = ChromeDriverManager().install()
        print(f"下载的ChromeDriver路径: {driver_path}")
        
        service = Service(driver_path)
        driver = webdriver.Chrome(service=service, options=options)
        print("✓ 方法3成功: 使用webdriver-manager初始化成功")
        
        # 测试打开网页
        print("\n测试打开百度...")
        driver.get("https://www.baidu.com")
        print(f"✓ 成功打开网页，当前标题: {driver.title}")
        
        # 关闭浏览器
        driver.quit()
        print("✓ 测试完成，浏览器已关闭")
        return
    except Exception as e:
        print(f"✗ 方法3失败: {str(e)}")
    
    # 所有方法都失败
    print("\n✗ 所有初始化方法均已失败")
    print("\n建议解决方案:")
    print("1. 确保已安装最新版Chrome浏览器")
    print("2. 手动下载与Chrome版本匹配的ChromeDriver")
    print(f"   您的Chrome版本: {chrome_version}")
    print("   下载地址: https://chromedriver.chromium.org/downloads")
    print("3. 将ChromeDriver放在以下路径之一:")
    
    if platform.system() == "Darwin":  # macOS
        print("   - /usr/local/bin/chromedriver")
        print("   - 或使用 'brew install --cask chromedriver' 安装")
    elif platform.system() == "Windows":
        print("   - 添加到PATH环境变量")
        print("   - 或放在脚本同目录下")
    else:  # Linux
        print("   - /usr/bin/chromedriver")
        print("   - 或使用 'apt install chromium-chromedriver' (Ubuntu)")

if __name__ == "__main__":
    test_chrome_browser() 